import {
  responseSuccess,
  responseError,
} from '@/share/interface/standard';
import { AppDataSource } from '@/data-source';
import { Goods } from '@/entity/Goods';
import { Menu } from '@/entity/Menu';
import type { NextFunction, Request, Response } from 'express';

export class GoodsController {
  private goodsRepository = AppDataSource.getRepository(Goods);
  private menuRepository = AppDataSource.getRepository(Menu);

  /**
   * 获取商品列表
   * Method: GET
   */
  async get(req: Request) {
    const data = await this.goodsRepository.find();
    return responseSuccess(data);
  }

  /**
   * 添加商品、更新商品
   *
   * @param {string} req.body.name - 商品名称
   * @param {string} req.body.description - 商品描述
   * @param {string} req.body.img - 商品图片
   * @param {number} req.body.price - 商品价格
   * @param {number} req.body.sale - 商品销量
   * @param {number} req.body.menu_id - 关联的菜单ID
   *
   * @method POST
   * @route /goods
   */
  async addAndSave(req: Request, res: Response) {
    const { good_id, name, description, img, price, menu_id } =
      req.body;

    //  转base64
    const imgBase64 = img.replace(/^data:image\/\w+;base64,/, '');
    // const imgBuffer = Buffer.from(imgBase64, 'base64');

    /*     var reader = new FileReader();
    const response = await fetch(thumb);
    const blob = await response.blob();
    console.log(blob);
    reader.readAsDataURL(blob);
    reader.onload = async () => {
      const dataUrl = reader.result;
      const base64Str = dataUrl.split(',')[1]; // 提取Base64字符串
    };
    console.log(img); */

    if (!name) {
      return responseError('商品名称不能为空');
    }

    const menu = await this.menuRepository.findOne({
      where: { id: menu_id },
    });

    if (!menu) {
      return responseError('指定的菜单不存在');
    }

    await this.goodsRepository.save({
      good_id,
      name,
      description,
      img: imgBase64,
      price,
      menu: menu,
    });

    return responseSuccess('添加成功');
  }

  //   async upload(req: Request, res: Response) {
  //     // console.log(req)
  //     // 文件图片转base64
  //     // console.log(req.file)
  //     // 拿到图片表单数据file
  //     const file = req.file;
  //     console.log(file)

  //     return responseSuccess('上传成功');

  //   }

  /**
   * 删除商品
   * Method: delete
   *
   * @param {number} req.params.id - 商品ID
   */
  async delete(req: Request, res: Response) {
    const id = parseInt(req.params.good_id);
    const good = await this.goodsRepository.findOne({
      where: { id },
    });
    if (!good) {
      return responseError('商品不存在');
    }
    await this.goodsRepository.delete(id);
    return responseSuccess('删除成功');
  }
}
